import React from 'react';
import {
  Form,
  Input,
  Tooltip,
  Icon,
  Cascader,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  AutoComplete,
  Radio,
  Table,
  Popover,
  Modal,
  Popconfirm
} from 'antd';
import styles from './index.less';
import { connect } from 'dva';
import router from 'umi/router';
import Global from '@/components/Global';
import EditModal from './editModal';
const { Option } = Select;
const { Group } = Radio;
const creator = (type, payload) => ({ type, payload });

class CreateParagraph extends React.Component {
  state = {
    visible: false,
    value: '', //段落内容
    _id: '',
    id: '',
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch(creator('paragraph/getParagraphs'));
  }
  // 将字符串转成数组
  convertStrToArr = str => {
    let l = 0,
      r = 0,
      n = str.length;
    const separates = ['.', '。'];
    const result = [];
    while (r < n) {
      r++;
      if (separates.includes(str[r])) {
        result.push(str.slice(l, r + 1).trim());
        l = r + 1;
      }
    }
    return result;
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        const originArr = this.convertStrToArr(values.originText);
        const translationArr = this.convertStrToArr(values.translationText);
        const obj = {};
        obj.id = values.id;
        obj.englishTitle = values.englishTitle;
        obj.chineseTitle = values.chineseTitle;
        obj.subTitle = values.subTitle;
        obj.paragraph = values.paragraph;
        obj.author = values.author;
        obj.sourceUrl = values.sourceUrl;
        obj.content = JSON.stringify(
          originArr.map((item, i) => ({
            originText: item,
            translationText: translationArr[i],
            bold: false,
          })),
        );
        dispatch(creator('paragraph/createParagraph', obj)).then(res => {
          if (res.httpStatus === 200) {
            // this.setState({
            //   id: values.id,
            // });
            dispatch(creator('paragraph/getParagraphs'));
          }
        });
      }
    });
  };
  resetKeys = () => {
    const { form } = this.props;
    let paragraph = form.getFieldValue('paragraph') ? form.getFieldValue('paragraph') - 0 + 1 : '';
    form.setFieldsValue({ paragraph });
    form.setFieldsValue({ originText: '' });
    form.setFieldsValue({ translationText: '' });
  };
  resetAll = () => {
    this.props.form.resetFields();
  };
  confirm = (_id) => {
    const { dispatch } = this.props;
    dispatch(creator('paragraph/delParagraphs', _id)).then(res => {
      if (res.httpStatus === 200) {
        dispatch(creator('paragraph/getParagraphs', this.state.id));
      }
    });
  };
  operate = (text, _id, e) => {
    e.preventDefault();
    this.setState({ value: JSON.stringify(text), _id });
    this.toggle();
  };
  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };
  setValue = value => {
    this.setState({ value });
  };
  render() {
    const { paragraph } = this.props;

    const { getFieldDecorator } = this.props.form;
    const { paragraphs } = paragraph;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    const columns = [
      { title: 'id', dataIndex: 'id' },
      { title: '英语标题', dataIndex: 'englishTitle' },
      { title: '第几段', dataIndex: 'paragraph' },
      {
        title: '段落共几句',
        dataIndex: 'content',
        render: (text, record) => {
          let str = '';
          text.forEach(item => (str += JSON.stringify(item)));
          const content = <div style={{ width: 600 }}>{str}</div>;
          return (
            <>
              <Popover content={content}>{text.length}</Popover>
              <a
                style={{ marginLeft: 8 }}
                href="#"
                onClick={this.operate.bind(this, text, record._id)}
              >
                <Icon type="edit" />
              </a>
            </>
          );
        },
      },
      {
        title: '操作',
        render: (text, record) => (
          <Popconfirm
            title="确认删除吗?"
            onConfirm={this.confirm.bind(this,record._id)}
            // onCancel={this.cancel}
            okText="确定"
            cancelText="取消"
          >
            <a href="#">
              删除
            </a>
          </Popconfirm>
          
        ),
      },
    ];
    return (
      <Global>
        <Form {...formItemLayout} onSubmit={this.handleSubmit}>
          <Form.Item label="id">
            {getFieldDecorator('id', {
              rules: [
                {
                  required: true,
                  message: '请输入文章id!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="英文标题">
            {getFieldDecorator('englishTitle', {
              rules: [
                {
                  required: true,
                  message: '请输入英文标题!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="中文标题">
            {getFieldDecorator('chineseTitle', {
              rules: [
                {
                  required: true,
                  message: '请输入中文标题!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="副标题">
            {getFieldDecorator('subTitle', {
              rules: [
                {
                  required: true,

                  message: '请输入文章副标题!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="第几段">
            {getFieldDecorator('paragraph', {
              rules: [
                {
                  required: true,
                  message: '请输入文章所属段落!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="原文">
            {getFieldDecorator('originText', {
              rules: [
                {
                  required: true,
                  message: '请输入原文!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="译文">
            {getFieldDecorator('translationText', {
              rules: [
                {
                  required: true,
                  message: '请输入译文!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="作者">
            {getFieldDecorator('author', {
              rules: [
                {
                  required: true,
                  message: '请输入作者名称!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="链接">
            {getFieldDecorator('sourceUrl', {
              rules: [
                {
                  required: true,
                  message: '请输入文章链接!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Row style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <Button type="primary" htmlType="submit">
              创建
            </Button>
            <Button type="primary" style={{ marginLeft: 8 }} onClick={this.resetKeys}>
              重置关键字段
            </Button>
            <Button type="primary" style={{ marginLeft: 8 }} onClick={this.resetAll}>
              重置所有字段
            </Button>
          </Row>
        </Form>
        <Table
          pagination={{
            total: paragraphs.length,
            showTotal: total => `共${total}条数据`,
            showSizeChanger: true,
            size: 'small',
            pageSizeOptions: ['10', '100', '1000'],
          }}
          style={{ marginTop: 10 }}
          rowKey="_id"
          dataSource={paragraphs}
          columns={columns}
        />
        <EditModal
          _id={this.state._id}
          value={this.state.value}
          visible={this.state.visible}
          toggle={this.toggle}
          setValue={this.setValue}
        />
      </Global>
    );
  }
}
//   export default CreateTitle

const WrappedCreateParagraph = Form.create({ name: 'paragraph' })(CreateParagraph);

export default connect(({ paragraph }) => ({ paragraph }))(WrappedCreateParagraph);
